package com.hongguan.oms.service.task;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.hongguan.oms.service.BaseService;
import com.hongguan.oms.utils.Util;

/**
 * @author <a href="mailto:gaoxinyi@hongguaninfo.com">gaoxy</a>
 * @version createTime:2010-1-4 ����06:15:31 summary
 */
@SuppressWarnings("unchecked")
@Service
public class TaskInfoService extends BaseService {
	public static final int BUFFER_SIZE = 16 * 1024;
	public TaskInfoService() {
		this.namespace = "Task";
	}

	public List searchTask(Map param) {
		return this.getSqlMapClientTemplate().queryForList(
				this.getStatementName("searchTaskInfo"), param);
	}

	public Long countTask(Map param) {
		return (Long) this.getSqlMapClientTemplate().queryForObject(
				this.getStatementName("countTaskInfo"), param);
	}

	public List searchTaskExes(String taskId) {
		String exes = (String) this.getSqlMapClientTemplate().queryForObject(
				this.getStatementName("searchTaskById2"), taskId);
		Map param = new HashMap();
		param.put("userId", exes.split(","));
		return this.getSqlMapClientTemplate().queryForList(
				this.getStatementName("searchTaskExes"), param);
	}
	public String searchSuperviseIdByTaskId(String taskId) {
		return (String) this.getSqlMapClientTemplate().queryForObject(
				this.getStatementName("searchSuperviseIdByTaskId"), taskId);
		
	}
	public Long getTaskId(){
		return (Long) this.getSqlMapClientTemplate().queryForObject(
				this.getStatementName("seqTaskInfo"));
	}
	public int addTask(Map param,Long taskId,int count) {
		
		//param.put("taskId", taskId);
		param.put("has_accessory", 0);
//		if(count==0){
//			param.put("has_accessory", 1);
//		}else{
//			param.put("has_accessory", 0);
//		}
		//param.put("taskId", taskId);
		//return (Integer)(this.getSqlMapClientTemplate().insert(this.getStatementName("addTask"), param)).intValue();
		return ((Integer)this.getSqlMapClientTemplate().insert(this.getStatementName("addTask"), param)).intValue();
//		if("send".equals(param.get("flag"))){
//			Long[] taskIds = {taskId};
//			Map param2 = new HashMap();
//			param2.put("taskId", taskIds);
//			this.addTaskExe(param2);
//		}
		//return taskId;
	}

	public void uptTask(Map param) {
/*		if(param.get("realFilePath") != null && !"".equals(param.get("realFilePath"))){
			param.put("has_accessory", 0);
		}else{
			param.put("has_accessory", 1);
		}*/
/*		if(param.get("has_accessory") != null && !"".equals(param.get("has_accessory"))){
			param.put("has_accessory", 0);
		}else{
			param.put("has_accessory", 1);
		}*/
		if(param.get("taskId")!=null&&!"".equals(param.get("taskId"))){
			long taskFileCount = this.searchTaskFileCount2(param.get("taskId").toString());	
			if(taskFileCount>0){
				param.put("has_accessory", 0);
			}else{
//				System.out.println("-----------�Ƿ��и�����"+"��");
				param.put("has_accessory", 1);
			}
		}
		
		this.getSqlMapClientTemplate().update(this.getStatementName("uptTask"),
				param);
/*		if(param.get("taskId")!=null&&!"".equals(param.get("taskId"))){
			if(param.get("realFilePath") != null && !"".equals(param.get("realFilePath"))){
				Map upLoadFile = new HashMap();
				String localFilePath = param.get("localFilePath").toString();
				File fileUpload = new File(param.get("realFilePath").toString());
				if(fileUpload!=null){
					String[] name =  fileUpload.getName().split("\\.");
					String fileTimeName = System.currentTimeMillis() + "." + name[1];
					if(name!=null&&name.length >= 2){
						System.out.println("---------�ϴ��ļ���·��Ϊ��----------"+localFilePath);
						uploadFile(fileUpload, fileTimeName, localFilePath);
						upLoadFile.put("accessory_name", fileUpload.getName());
						upLoadFile.put("buis_id", param.get("taskId").toString());
						upLoadFile.put("upload_date", new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
						upLoadFile.put("upload_name", fileTimeName);
						upLoadFile.put("file_type", 1);
						upLoadFile.put("file_path", "/upfile/taskfile");
						upLoadFile.put("file_size", fileUpload.length());
						savaFileUploadInfo(upLoadFile);
					}
				}
			}
		}*/
	}
	/**
	 * delTask
	 * @param param
	 */
	public void delTask(Map param) {
		this.getSqlMapClientTemplate().delete(this.getStatementName("delTask"),param);
	}
	
	public void uptTaskStatus(Map param) {
		this.getSqlMapClientTemplate().update(
				this.getStatementName("uptTaskStatus"), param);
	}

	public List searchTaskExe(Map param) {
		return this.getSqlMapClientTemplate().queryForList(
				this.getStatementName("searchTaskExecutor"), param);
	}
	public Map getLastFeedBackMessage(Map param) {
		return (Map)this.getSqlMapClientTemplate().queryForObject(this.getStatementName("getLastFeedBackMessage"), param);
	}
	public Long countTaskExe(Map param) {
		return (Long) this.getSqlMapClientTemplate().queryForObject(
				this.getStatementName("countTaskExecutor"), param);
	}
	
	public List reviewTask(Map param) {
		return this.getSqlMapClientTemplate().queryForList(
				this.getStatementName("reviewTask"), param);
	}
	public Long reviewTaskCount(Map param) {
		return (Long) this.getSqlMapClientTemplate().queryForObject(
				this.getStatementName("reviewTaskCount"), param);
	}
	/**
	 * ����ִ���ߵĽ�ɫҲ���ǵ�¼�û���ɫ���ɷ��ߵ�ID�ж��Ƿ����ϼ��ɷ�
	 * @param Map
	 * @param boolean
	 * @return
	 * @throws Exception
	 */
	public boolean volidateDispatcher(Map map){
		Long allRoleSize = (Long)this.getSqlMapClientTemplate().queryForObject(this.getStatementName("volidateDispatcher"), map);
		if(allRoleSize>0){
			return true;
		}else{
			return false;
		}
	}
	public void addTaskExe(Map param) { // ...
		List<Map> tasks = this.getSqlMapClientTemplate().queryForList(
				this.getStatementName("searchTaskById"), param);
		for (Map task : tasks) {
			for (String exe : ((String) task.get("TASK_EXECUTOR")).split(",")) {
				task.put("userId", exe);
				Long exeId = (Long) this.getSqlMapClientTemplate().queryForObject(this.getStatementName("seqTaskExe"));
				task.put("exeId", exeId);
				task.put("performType", "0");
				this.getSqlMapClientTemplate().insert(
						this.getStatementName("addTaskExecutor"), task);
				Map log = new HashMap();
				log.put("from", task.get("TASK_DISPATCHER"));
				log.put("to", exe);
				log.put("taskId", exeId);
				log.put("task_status", "0");
				this.recordLog(log);
			}
		}
	}

	public void uptTaskExe(Map param) {
		this.getSqlMapClientTemplate().update(
				this.getStatementName("uptTaskExecutor"), param);
		if("3".equals(param.get("status"))){
			if((Long) this.getSqlMapClientTemplate().queryForObject(this.getStatementName("countTaskByComplete"),(String)param.get("taskId")) == 0){
				Map param2 = new HashMap();
				param2.put("taskId", param.get("taskId"));
				param2.put("task_status", "2");
				this.getSqlMapClientTemplate().update(this.getStatementName("uptTask"),param2);
			}
		}else if("4".equals(param.get("status"))){
			if((Long) this.getSqlMapClientTemplate().queryForObject(this.getStatementName("countTaskByComplete"),(String)param.get("taskId")) == 0){
				Map param2 = new HashMap();
				param2.put("taskId", param.get("taskId"));
				param2.put("task_status", "4");
				this.getSqlMapClientTemplate().update(this.getStatementName("uptTask"),param2);
			}
		}
	}

	public void uptTaskExeStatus(Map param) {
		this.getSqlMapClientTemplate().update(
				this.getStatementName("uptTaskExeStatus"), param);
	}

	public void addFeedBack(Map param) {
		this.getSqlMapClientTemplate().insert(
				this.getStatementName("addFeedBack"), param);
	}

	public void zfTask(Map param) {
		this.uptTaskExeStatus(param);
		param.put("exeId", this.getSqlMapClientTemplate().queryForObject(this.getStatementName("seqTaskExe")));
		param.put("performType", "0");
		this.getSqlMapClientTemplate().insert(
				this.getStatementName("addTaskExecutor"), param);
		this.recordLog(param);
		param.put("taskId", param.get("exeId"));
		this.recordLog(param);
	}
	
	public List searchTaskHistory(String exeId){
		return this.getSqlMapClientTemplate().queryForList(this.getStatementName("searchTaskHistory"),exeId);
	}
	
	public List searchTaskFeedBack(String exeId){
		return this.getSqlMapClientTemplate().queryForList(this.getStatementName("searchFeedBack"),exeId);
	}
	/**
	 * get deptName and deptId
	 * @param map
	 * @return
	 */
	public List getBranchInfo(Map map){
		return this.getSqlMapClientTemplate().queryForList(this.getStatementName("getBranchByUserBranch"),map);
	}
	/**
	 * get deptuserids 
	 * @param map
	 * @return
	 */
	public List getDeptUserIds(String branchId){
		return this.getSqlMapClientTemplate().queryForList(this.getStatementName("getDeptUserIds"),branchId);
	}
	public void recordLog(Map param) {
		this.getSqlMapClientTemplate().insert(
				this.getStatementName("addTaskHistory"), param);
	}

	public long getUnfinished(String userId) {
		Map params = new HashMap();
		params.put("userId", userId);
		params.put("status", 1);
		return (Long)this.getSqlMapClientTemplate().queryForObject(
				this.getStatementName("countTaskExecutorStatus"), params);
	}
	//ȫԱ֪��
	public String getNoteTasks(String userId){
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("userId", userId);
		param.put("beginRow", 0);
		param.put("endRow", 3);
		param.put("taskOrigin", 10);
		List<Map> list=this.getSqlMapClientTemplate().queryForList(
				this.getStatementName("searchTaskExecutor"), param);
		StringBuffer result=new StringBuffer();
		if(list==null||list.isEmpty())
			return "��";
		for(Map<String,Object> task:list){
			String name=(String)task.get("TASK_TITLE");
			result.append(name).append(";");
		}
		return result.toString();
	}
	
	/**
	 * getExpiredTask
	 * @param userId
	 * @return
	 */
	public long getExpiredTask(String userId) {
		Map params = new HashMap();
		params.put("userId", userId);
		params.put("status", 3);
		return (Long)this.getSqlMapClientTemplate().queryForObject(
				this.getStatementName("getExpiredTask"), params);
	}	
	public long getTaken(String userId) {
		Map params = new HashMap();
		params.put("userId", userId);
		params.put("status", 0);
		return (Long)this.getSqlMapClientTemplate().queryForObject(
				this.getStatementName("countTaskExecutorStatus"), params);
	}
	
	public List watchTaskPlan(Map param){
		return this.getSqlMapClientTemplate().queryForList("Task.watchSearchTask",param);
	}
	
	public long countTaskPlan(Map param){
		return (Long) this.getSqlMapClientTemplate().queryForObject("Task.watchSearchTaskCount",param);
	}
	
	public List watchTaskItemByTask(String taskId){
		return this.getSqlMapClientTemplate().queryForList("Task.watchTaskItemByTask",taskId);
	}
	/**
	 * 取得登录用户以及子用户ID
	 * @param roleId
	 * @return
	 * @author qiaozhongchao create by 2010-1-20
	 */
	public List<String> getSubUserId(String roleId){
		return this.getSqlMapClientTemplate().queryForList(this.getStatementName("getSubUserIds"), roleId);
	}
	public List getUserPhoneAndMail(String taskId){
		return this.getSqlMapClientTemplate().queryForList(this.getStatementName("getUserPhoneAndMail"),taskId);
	}
	public Map getUserPhoneAndMailByUserId(String userId){
		return (Map)this.getSqlMapClientTemplate().queryForObject(this.getStatementName("getUserPhoneAndMailByUserId"),userId);
	}
	public Map getTaskInfo(String taskId){
		return (Map)this.getSqlMapClientTemplate().queryForObject(this.getStatementName("getTaskInfo"),taskId);
	}
	public List getUserInfo(String[] userIds){
		Map map = new HashMap();
		map.put("userIds", userIds);
		return (List)this.getSqlMapClientTemplate().queryForList(this.getStatementName("queryByUserId"),map);
	}
	/**
	 * �ϴ��ļ�
	 * @author ���г�
	 * @param 
	 * fileUpload��Ҫ�ϴ����ļ�
	 * fileUploadFileName:�ϴ����ļ�����ƣ�ID��
	 * filePath���ļ��ϴ���·��
	 * @return void
	 */
	public void uploadFile(File fileUpload, String fileUploadFileName, String filePath) {
		try {
			File uploadFile = new File(filePath, fileUploadFileName);
	        OutputStream outputStream = new FileOutputStream(uploadFile);
	        BufferedInputStream bufferedInputStream = null;
	        BufferedOutputStream bufferedOutputStream = null;
	        
            bufferedInputStream = new BufferedInputStream(new FileInputStream(fileUpload));
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            final byte temp[] = new byte[BUFFER_SIZE];
            int readBytes = 0;
            while ((readBytes = bufferedInputStream.read(temp)) != -1) {
                bufferedOutputStream.write(temp, 0, readBytes);
            }
            bufferedOutputStream.flush();           
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
	}
	/**
	 * �ϴ��ļ�д����ݿ�
	 * @author ���г�
	 * @param Map
	 * @return void
	 */
	public void savaFileUploadInfo(Map param) {
		this.getSqlMapClientTemplate().insert(this.getStatementName("saveTaskAccessoryInfo"), param);
	}	
	/**
	 * ��ѯ�ϴ�������Ϣ
	 * @author ���г�
	 * @param Map
	 * @return void
	 */
	public List searchTaskUpLoadFile(Map param) {
		return this.getSqlMapClientTemplate().queryForList(this.getStatementName("searchTaskUpLoadFile"), param);
	}
	/**
	 * ��ѯ�ϴ�������Ϣ��¼��
	 * @author ���г�
	 * @param Map
	 * @return void
	 */	
	public long searchTaskUpLoadFileCount(Map param){
		return (Long) this.getSqlMapClientTemplate().queryForObject(this.getStatementName("searchTaskUpLoadFileCount"), param);
	}
	/**
	 * ɾ���
	 * @author ���г�
	 * @param Map
	 * @return void
	 */	
	public void delTaskUploadFile(String buis_id) {
		this.getSqlMapClientTemplate().delete(this.getStatementName("delTaskUploadFile"),buis_id);
	}
	public void delMulUploadFile(Map param) {
		this.getSqlMapClientTemplate().delete(this.getStatementName("delMulUploadFile"), param);
	}
	/**
	 * ȡ�ø�����Ϣ
	 * @author ���г�
	 * @param Map
	 * @return void
	 */	
	public Map getUploadFileInfo(String fileId){
		return (Map)this.getSqlMapClientTemplate().queryForObject(this.getStatementName("getUploadFileInfo"),fileId);
	}
	/**
	 * ��ѯ�ϴ�������Ϣ��¼��
	 * @author ���г�
	 * @param Map
	 * @return void
	 */	
	public long searchTaskFileCount(String buis_Id){
		return (Long) this.getSqlMapClientTemplate().queryForObject(this.getStatementName("searchTaskFileCount"), buis_Id);
	}
	/**
	 * ��ѯ�ϴ�������Ϣ��¼��������ID
	 * @author ���г�
	 * @param Map
	 * @return void
	 */	
	public long searchTaskFileCount2(String taskId){
		return (Long) this.getSqlMapClientTemplate().queryForObject(this.getStatementName("searchTaskFileCount2"), taskId);
	}
	/**
	 * ��ѯ�����·��󣬸���ִ���˵�ִ�����
	 * ��¼
	 * @author ���г�
	 * @param Map
	 * @return void
	 */
	public List searchTaskExeStatus(Map param) {
		return this.getSqlMapClientTemplate().queryForList(this.getStatementName("searchTaskExeStatus"), param);
	}
	/**
	 * ��ѯ�����·��󣬸���ִ���˵�ִ�����
	 * ��¼����
	 * @author ���г�
	 * @param Map
	 * @return void
	 */	
	public long searchTaskExeStatusCount(Map param){
		return (Long) this.getSqlMapClientTemplate().queryForObject(this.getStatementName("searchTaskExeStatusCount"), param);
	}
	/**
	 * ��ѯ�߰����
	 * ��¼
	 * @author ���г�
	 * @param Map
	 * @return void
	 */
	public List searchTaskRemind(Map param) {
		return this.getSqlMapClientTemplate().queryForList(this.getStatementName("searchTaskRemind"), param);
	}
	/**
	 * ��ѯ�߰����
	 * ��¼����
	 * @author ���г�
	 * @param Map
	 * @return void
	 */	
	public long searchTaskRemindCount(Map param){
		return (Long) this.getSqlMapClientTemplate().queryForObject(this.getStatementName("searchTaskRemindCount"), param);
	}
	/**
	 * OA�Ż���ѯ����¼��
	 * @author ���г�
	 * @param String
	 * @return void
	 */	
	public long getToDoCount(String userLoginId){
		long taskCount = (Long)this.getSqlMapClientTemplate().queryForObject(this.getStatementName("getToDoTaskCount"), userLoginId);
		long planCount = (Long)this.getSqlMapClientTemplate().queryForObject(this.getStatementName("getToDoAuditCount"), userLoginId);
		long superviseCount = (Long)this.getSqlMapClientTemplate().queryForObject(this.getStatementName("getToDoSuperviseCount"), userLoginId);
		return taskCount+planCount+superviseCount;
	}
	/**
	 * �������߰�
	 * 
	 */
	public void addTaskCc(Map map){
		this.getSqlMapClientTemplate().insert(this.getStatementName("addTaskCc"), map);
	}
	
	/**
	 * �ͻ�������������ӷ������˷�����������
	 * @param suffix
	 * @return
	 */
	public String getContentType(String suffix) { 
		String contentType = null; 
		if (suffix.equals(".avi")) { 
		contentType = "video/avi"; 
		} else if (suffix.equals(".bmp")) { 
		         contentType = "application/x-bmp"; 
		} else if (suffix.equals(".doc")) { 
		contentType = "application/msword"; 
		} else if (suffix.equals(".gif")) { 
		contentType = "image/gif"; 
		} else if (suffix.equals(".htm") || suffix.equals(".html")) { 
		contentType = "text/html"; 
		} else if (suffix.equals(".jpg") || suffix.equals(".jpeg")) { 
		contentType = "image/jpeg"; 
		} else if (suffix.equals(".mht") || suffix.equals(".mhtml")) { 
		contentType = "message/rfc822"; 
		} else if (suffix.equals(".mp3")) { 
		contentType = "audio/mp3"; 
		} else if (suffix.equals(".ppt")) { 
		         contentType = "application/vnd.ms-powerpoint"; 
		} else if (suffix.equals(".pptx")) { 
		contentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; 
		} else if (suffix.equals(".rm")) { 
		contentType = "application/vnd.rn-realmedia"; 
		} else if (suffix.equals(".rmvb")) { 
		contentType = "application/vnd.rn-realmedia-vbr"; 
		} else if (suffix.equals(".xls")) { 
		contentType = "application/x-xls"; 
		} else if (suffix.equals(".xml")) { 
		contentType = "text/xml"; 
		} else if (suffix.equals(".rar")) { 
		contentType = "application/octet-stream"; 
		} else if (suffix.equals(".zip")) { 
		contentType = "application/x-zip-compressed"; 
		} else if (suffix.equals(".swf")) { 
		contentType = "application/x-shockwave-flash"; 
		} else if (suffix.equals(".wav")) { 
		         contentType = "audio/wav"; 
		} else if (suffix.equals(".txt")) { 
		contentType = "text/plain"; 
		} 
		return contentType; 
		} 
}
